/**
 * 构建二叉树
 */

class BinarySearchTree {
	constructor(val) {
		this.root = {};
		this.root.val = val;
		this.root.left = null;
		this.root.right = null;
		this.insert = this.insert.bind(this);
	}

	insert(key) {
		const newNode = new Node(key);
		/**
		 * [将一个新的节点插入到二叉搜索树]
		 * @param  {[type]} node    [需要插入的目标节点]
		 * @param  {[type]} newNode [构建的新的节点]
		 * @return {[type]}         [当前二叉树]
		 */
		const insertNode = (node, newNode) => {
			if (newNode.val < node.val) {
				if (node.left == null) {
					node.left = newNode;
				} else {
					insertNode(node.left, newNode);
				}
			} else {
				if (node.right == null) {
					node.right = newNode;
				} else {
					insertNode(node.right, newNode);
				}
			}
		}
		if (this.root == null) {
			this.root = newNode;
		} else {
			insertNode(this.root, newNode);
		}
		return this.root;
	}
}


class Node {
	constructor(val) {
		this.val = val;
		this.left = null;
		this.right = null;
	}
}


module.exports = BinarySearchTree;